package com.hqyj.freemovie.front.test;

import java.util.concurrent.*;
class SaleWindowRunnable implements Runnable {

    private final SaleWindow saleWindow;

    public SaleWindowRunnable(SaleWindow saleWindow) {
        this.saleWindow = saleWindow;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (saleWindow) {
                if (Ticket.TICKET_NUM <= 0) {
                    System.out.println("今天的门票全部售完！！");
                    break;
                }

                Ticket.TICKET_NUM--;
                if ("窗口A".equals(Thread.currentThread().getName())) {
                    System.out.println("A窗口售出一张票，还剩：" + Ticket.TICKET_NUM + "张门票...");
                    saleWindow.windowsASaleNumber++;
                }
                if ("窗口B".equals(Thread.currentThread().getName())) {
                    System.out.println("B窗口售出一张票，还剩：" + Ticket.TICKET_NUM + "张门票...");
                    saleWindow.windowsBSaleNumber++;
                }
                if ("窗口C".equals(Thread.currentThread().getName())) {
                    System.out.println("C窗口售出一张票，还剩：" + Ticket.TICKET_NUM + "张门票...");
                    saleWindow.windowsCSaleNumber++;
                }
            }
        }
    }
}

public class TicketDemoWithPool {

    //阻塞式关闭线程池。
    public static void awaitAfterShutdown(ExecutorService threadPool) {
        threadPool.shutdown();
        try {
            if (!threadPool.awaitTermination(200, TimeUnit.SECONDS)) {
                threadPool.shutdownNow();
            }
        } catch (InterruptedException ex) {
            threadPool.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }

    public static void main(String[] args) {

        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(3, 10, 3,
                TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3), new ThreadFactory() {
            final String[] profix = {"A", "B", "C"};
            int index = 0; //计数器.... //第一个线程就是：'小张',第二个就是'小李',以此类推.....
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "窗口" + profix[index++]);
            }
        }, new ThreadPoolExecutor.DiscardOldestPolicy());


        Ticket ticket = new Ticket();
        SaleWindow saleWindow = new SaleWindow(ticket);

        SaleWindowRunnable saleWindowRunnable = new SaleWindowRunnable(saleWindow);
        threadPool.submit(saleWindowRunnable);
        threadPool.submit(saleWindowRunnable);
        threadPool.submit(saleWindowRunnable);

        awaitAfterShutdown(threadPool);

        System.out.println("A窗口卖了："+saleWindow.windowsASaleNumber+"张票");
        System.out.println("B窗口卖了："+saleWindow.windowsBSaleNumber+"张票");
        System.out.println("C窗口卖了："+saleWindow.windowsCSaleNumber+"张票");
    }

}
